package com.bst;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class TranslateAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        // 获取选中的文本
        String selectedText = e.getData(CommonDataKeys.EDITOR).getSelectionModel().getSelectedText();
        if (selectedText == null || selectedText.trim().isEmpty()) {
            showErrorBalloon(e, "请先选择要翻译的文本");
            return;
        }

        // 检查配置
        BaiduTranslateSettings settings = BaiduTranslateSettings.getInstance();
        if (!settings.isConfigured()) {
            int result = Messages.showYesNoDialog(
                    "尚未配置百度翻译API，请先配置APP ID和密钥",
                    "配置提示",
                    "去配置",
                    "取消",
                    Messages.getInformationIcon()
            );
            
            if (result == Messages.YES) {
                ShowSettingsUtil.getInstance().showSettingsDialog(
                        e.getProject(), 
                        BaiduTranslateConfigurable.class
                );
            }
            return;
        }

        // 执行翻译
        try {
            BaiduTranslateService translator = new BaiduTranslateService(
                    settings.appId,
                    settings.appKey
            );
            
            BaiduTranslateService.TranslationResult result = translator.translate(
                    selectedText,
                    settings.defaultFrom,
                    settings.defaultTo
            );
            
            if (result.isSuccess() && result.trans_result != null && result.trans_result.length > 0) {
                StringBuilder translation = new StringBuilder();
                for (BaiduTranslateService.Translation trans : result.trans_result) {
                    translation.append(trans.dst).append("\n");
                }
                showTranslationBalloon(e, translation.toString().trim());
            } else {
                showErrorBalloon(e, "翻译失败: " + (result.error_msg != null ? result.error_msg : "未知错误"));
            }
        } catch (IOException ex) {
            showErrorBalloon(e, "翻译请求出错: " + ex.getMessage());
        } catch (Exception ex) {
            showErrorBalloon(e, "发生错误: " + ex.getMessage());
        }
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        // 只有选中文本时才启用该动作
        boolean hasSelection = e.getData(CommonDataKeys.EDITOR) != null &&
                e.getData(CommonDataKeys.EDITOR).getSelectionModel().hasSelection();
        e.getPresentation().setEnabledAndVisible(hasSelection);
    }

    private void showTranslationBalloon(AnActionEvent e, String text) {
        JBPopupFactory.getInstance()
                .createHtmlTextBalloonBuilder(text, null, JBColor.WHITE, null)
                .setFadeoutTime(10000)
                .createBalloon()
                .show(RelativePoint.getCenterOf(e.getData(CommonDataKeys.EDITOR).getComponent()), Balloon.Position.below);
    }

    private void showErrorBalloon(AnActionEvent e, String message) {
        JBPopupFactory.getInstance()
                .createHtmlTextBalloonBuilder(message, null, JBColor.RED, null)
                .setFadeoutTime(5000)
                .createBalloon()
                .show(RelativePoint.getCenterOf(e.getData(CommonDataKeys.EDITOR).getComponent()), Balloon.Position.below);
    }
}
